// 状态映射表
const statusMap = {
	3: { class: 'status-success', text: '已使用' },
	2: { class: 'status-error', text: '已校验' },
	1: { class: 'status-pending', text: '待使用' }
};

// 验证码类型映射
// 验证码类型映射
const typeMap = {
	1: "注册验证码",
	2: "找回登录密码",
	3: "找回交易密码",
	4: "修改手机号码第一步",
	5: "修改手机号码第二步",
	6: "添加邮箱",
	7: "修改邮箱",
	10: "见证人为客户创建账号验证码",
	11: "第三方社交账号绑定",
	12: "第三方社交账号直接绑定",
	13: "登录密码初始设置",
	14: "第三方授权认证",
	15: "第三方快速登录",
	16: "用户设备绑定",
	17: "用户交易登录",
	18: "投顾-找回登录密码",
	19: "投顾-手机快速登录",
	20: "修改双因素验证",
	21: "身份验证",
	22: "開戶-香港PAD見證-簽名上傳",
	23: "验证码登录注册",
	24: "找回交易账号",
	25: "快速登录",
	26: "修改开户邮箱",
	27: "第三方sdk找回交易密码",
	28: "通用验证码",
	29: "添加证券邮箱",
	30: "修改证券邮箱-验证原邮箱",
	31: "修改证券邮箱-验证新邮件",
	32: "修改证券邮箱-废弃",
	33: "企业portal-修改资料",
	34: "企业portal-添加银行卡",
	35: "企业portal-存入资金",
	36: "企业portal-取出资金",
	37: "企业portal-资金内转",
	38: "企业portal-证期互转",
	39: "企业portal-货币兑换",
	40: "企业portal-股票转入",
	41: "企业portal-股票转出",
	42: "企业portal-股票内转",
	43: "企业portal-基金内转",
	44: "企业portal-债券内转"
};

const AUTO_FILL_INTERVAL = 1500;
let latestSmsList = [];
let autoFillTimerId = null;
let autoFillCheckInProgress = false;

// 定时检测被调试页面中的手机号输入并尝试自动填充验证码
function startAutoFillWatcher() {
	if (autoFillTimerId) {
		return;
	}
	autoFillTimerId = setInterval(checkAndFillMobileCode, AUTO_FILL_INTERVAL);
}

function checkAndFillMobileCode() {
	if (autoFillCheckInProgress) {
		return;
	}
	if (!Array.isArray(latestSmsList) || latestSmsList.length === 0) {
		return;
	}

	autoFillCheckInProgress = true;
	const inspectScript = `(function() {
		const mobileInput = document.querySelector('input[type="tel"][name="mobile"][placeholder="请输入手机号码"].input_tel');
		if (!mobileInput) {
			return { hasMobileInput: false };
		}
		const codeInput = document.querySelector('input[type="tel"][name="mobileCode"][placeholder="请输入收到的短信验证码"]');
		return {
			hasMobileInput: true,
			mobileValue: mobileInput.value || '',
			hasCodeInput: !!codeInput,
			codeValue: codeInput ? (codeInput.value || '') : ''
		};
	})();`;

	chrome.devtools.inspectedWindow.eval(inspectScript, (result, isException) => {
		autoFillCheckInProgress = false;
		if (isException || !result || !result.hasMobileInput) {
			return;
		}

		const mobileValue = (result.mobileValue || '').trim();
		if (!mobileValue) {
			return;
		}

		const matchedRecord = latestSmsList.find(item => String(item.mobile || '').trim() === mobileValue && item.auth_code);
		if (!matchedRecord) {
			return;
		}

		if (!result.hasCodeInput) {
			return;
		}

		const desiredCode = String(matchedRecord.auth_code || '').trim();
		if (!desiredCode || (result.codeValue && result.codeValue.trim() === desiredCode)) {
			return;
		}

		const fillScript = `(function() {
			const codeInput = document.querySelector('input[type="tel"][name="mobileCode"][placeholder="请输入收到的短信验证码"]');
			if (!codeInput) {
				return false;
			}
			codeInput.focus();
			codeInput.value = ${JSON.stringify(desiredCode)};
			codeInput.dispatchEvent(new Event('input', { bubbles: true }));
			codeInput.dispatchEvent(new Event('change', { bubbles: true }));
			codeInput.dispatchEvent(new Event('blur', { bubbles: true }));
			return true;
		})();`;
		chrome.devtools.inspectedWindow.eval(fillScript, (filled, fillException) => {
			if (fillException) {
				console.warn('自动填充验证码失败:', fillException);
			} else if (filled) {
				console.log('已自动填写验证码:', desiredCode);
			}
		});
	});
}

// 数据请求函数
async function fetchData() {
	// 显示加载动画
	const phone = document.querySelector('.phone-filter').value.trim();
	let env = document.querySelector('.env-filter').value;
	// 显示加载动画
	document.querySelector('.loader').style.display = 'block';
	document.querySelector('.error-message').style.display = 'none';
	// 构造请求参数
	const params = new URLSearchParams();
	if (phone) params.append('mobile', phone);
	if (!env){
		env = "feature";
	}
	params.append('profile', env); // 假设profile对应环境参数
	const url = `https://admin-feature.vbkrhk.com/auto-ai/sms/list?${params}`;
	try {
		const response = await fetch(url);
		const data = await response.json();
		// 隐藏加载动画
		document.querySelector('.loader').style.display = 'none';
		if (data.code === 0) {
			latestSmsList = Array.isArray(data.data) ? data.data : [];
			renderTable(latestSmsList);
			checkAndFillMobileCode();
		} else {
			latestSmsList = [];
			document.querySelector('.error-message').textContent = data.msg || '请求失败';
			document.querySelector('.error-message').style.display = 'block';
		}
	} catch (error) {

		document.querySelector('.error-message').textContent = '网络错误';
		document.querySelector('.error-message').style.display = 'block';
	}
}
// 复制事件处理函数
let copyToastTimer = null;

function showCopyToast(message) {
	const toast = document.getElementById('copy-toast');
	if (!toast) return;
	toast.textContent = message;
	toast.classList.add('show');
	if (copyToastTimer) {
		clearTimeout(copyToastTimer);
	}
	copyToastTimer = setTimeout(() => {
		toast.classList.remove('show');
	}, 1500);
}

async function copyTextToClipboard(text) {
	if (navigator.clipboard && navigator.clipboard.writeText) {
		try {
			await navigator.clipboard.writeText(text);
			return;
		} catch (error) {
			console.warn('📋 使用 Clipboard API 失败，尝试降级处理:', error);
		}
	}
	// 兼容处理
	try {
		const textarea = document.createElement('textarea');
		const selection = document.getSelection();
		const originalRange = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

		textarea.value = text;
		textarea.style.position = 'fixed';
		textarea.style.opacity = '0';
		document.body.appendChild(textarea);
		textarea.focus();
		textarea.select();

		let successful = false;
		try {
			successful = document.execCommand('copy');
		} finally {
			if (selection) {
				selection.removeAllRanges();
				if (originalRange) {
					selection.addRange(originalRange);
				}
			}
			if (textarea.parentNode) {
				textarea.parentNode.removeChild(textarea);
			}
		}

		if (!successful) {
			throw new Error('Fallback copy failed');
		}
	} catch (error) {
		throw error;
	}
}

function handleCopy(event) {
	const cell = event.currentTarget;
	const text = cell.textContent.trim();
	if (!text) return;

	copyTextToClipboard(text)
		.then(() => {
			console.log('✅ 复制成功:', text);
			cell.style.backgroundColor = '#eaffea';
			showCopyToast('验证码已复制');
			setTimeout(() => {
				cell.style.backgroundColor = '';
			}, 1000);
		})
		.catch(error => {
			console.error('❌ 复制失败:', error);
			showCopyToast('复制失败，请手动复制');
		});
}
// 表格渲染函数
function renderTable(data) {
	const tbody = document.querySelector('tbody');
	tbody.innerHTML = ''; // 清空原有数据
	data.forEach(item => {
		const row = document.createElement('tr');

		const mobileCell = document.createElement('td');
		mobileCell.textContent = item.mobile;
		row.appendChild(mobileCell);

		const codeCell = document.createElement('td');
		codeCell.textContent = item.auth_code;
		// 绑定复制事件（双击复制）
		codeCell.addEventListener('dblclick', handleCopy);
		row.appendChild(codeCell);

		const typeCell = document.createElement('td');
		typeCell.textContent = typeMap[item.auth_type] || '未知';
		row.appendChild(typeCell);

		const statusCell = document.createElement('td');
		const statusSpan = document.createElement('span');
		statusSpan.className = `status ${statusMap[item.use_status]?.class || 'status-pending'}`;
		statusSpan.textContent = statusMap[item.use_status]?.text || '未知';
		statusCell.appendChild(statusSpan);
		row.appendChild(statusCell);

		const memberIdCell = document.createElement('td');
		memberIdCell.textContent = item.member_id || '无';
		row.appendChild(memberIdCell);

		tbody.appendChild(row);
	});
}

document.getElementById('filter-btn').addEventListener('click', function() {
	fetchData();
});

// panel.js
document.addEventListener("DOMContentLoaded", async () => {
	try {
		// 获取当前页面的 URL
		const url = await new Promise((resolve) => {
			chrome.devtools.inspectedWindow.eval(
				"location.href",
				(result, isException) => {
					if (isException) {
						resolve("无法获取 URL");
					} else {
						resolve(result);
					}
				}
			);
		});

		// 检测 URL 是否包含 "feature"
		const containsFeature = url.includes("feature");
		const containsDaily = url.includes("daily");
		// 获取 select 元素
		const envSelect = document.querySelector('.env-filter');
		// 设置选中值为 "feature"
		let profile = null;
		if (containsDaily) {
			profile = 'daily';
			envSelect.value = 'daily';
		}else if (containsFeature) {
			profile = 'feature';
			envSelect.value = 'feature';
		}
		const environmentMessage = document.querySelector('.environment-message');
		environmentMessage.innerHTML = `
				检测您当前环境为 
				<span class="current-env">${profile}</span> 
					环境，如下是 
				<span class="current-env">${profile}</span> 
				环境最新5条
					`;
		fetchData(); // 页面加载时自动获取数据
		startAutoFillWatcher();
		const intervalId = setInterval(() => {
			// 要执行的代码
			fetchData();
		}, 1000); // 3000 毫秒 = 3秒
	} catch (error) {
		console.error("错误:", error);
		document.getElementById("result").innerText = "检测失败，请重试。";
	}
});
var myconsole =
{
	_log: function(obj)
	{
		// 不知为何，这种方式不行
		chrome.devtools.inspectedWindow('console.log('+JSON.stringify(obj)+')');
	},
	log: function(obj)
	{
		// 这里有待完善
		chrome.tabs.executeScript(chrome.devtools.inspectedWindow.tabId, {code: 'console.log(' + JSON.stringify(obj) + ')'}, function(){});
	}
};
